module.exports = function ($state, $resource, toaster) {

	return {

		restrict: 'E',
		template: require('../views/priceStandard.html'),
		replace: true,
		scope: {
			'saleobj': '=',
			'funobj': '=',
			'baseinfo': '=',
			'util': '='
		},
		link: function (scope, elements, attrs) {
			var back_data = {};					//记录已经填写的价格信息，不刷新页面情况下会无限新数据
			scope.formdata = {
				'id': scope.saleobj.id, 		//标签页暂存产品id
				'code': scope.saleobj.code,		//标签页暂存产品编号
				'showitem': [],					//记录刷新后规格表内要显示的规格名称
			};
			scope.tabletitle = [];				//上半部规格名称+规格项（二维数组）
			scope.tabledata = [];				//下半部规格明细表数据

			function setTabelData(tabelData, srcData){
				tabelData.forEach(element => {
					var sku = '', a = scope.formdata.showitem.length;
					for(var i = 0; i < a; i++){
						sku += ',' + element['name'+i];
					}
					sku = sku.substring(1);
					var temp = srcData[sku];
					if(temp){
						element.stock_num = temp.stock_num;
						element.market_price = temp.market_price;
						element.guide_price = temp.guide_price;
						element.cost_price = temp.cost_price;
						element.purchase_price = temp.purchase_price;
					}
				});
			}

			scope.save = function () {
				if(!scope.tabledata ||  scope.tabledata.length == 0){
					toaster.warning({ title: '', body: '未设置规格信息，无法保存'});
					return;
				}
				var price_list = [];
				for(var i2 = 0; i2 < scope.tabledata.length; i2++){
					var element = scope.tabledata[i2];
					if(element.stock_num < 0){
						toaster.warning({ title: '', body: '库存不能为负数'});
						return;
					}
					if((!element.market_price || element.market_price < 0) 
						|| (!element.guide_price || element.guide_price < 0) 
						|| (!element.cost_price || element.cost_price < 0)
						|| (!element.purchase_price || element.purchase_price < 0)){

						toaster.warning({ title: '', body: '产品的价格不能小于0元'});
						return;
					}
					
					var temp = {
						'sku': '',
						'stock_num': element.stock_num || 0,
						'market_price': (element.market_price||0) * 100,
						'guide_price': (element.guide_price||0) * 100,
						'cost_price': (element.cost_price||0) * 100,
						'purchase_price': (element.purchase_price||0) * 100
					};
					for(var i = 0; i < scope.formdata.showitem.length; i++){
						temp.sku += ',' + element['name'+i];
					}
					temp.sku = temp.sku.substring(1);
					price_list.push(temp);
				}
				var para = {
					'sale_code': scope.saleobj.code,
					'sku_list': scope.skulist,
					'price_list': price_list
				}
				
				$resource('/api/ac/tc/ticketSaleSKUService/saveSaleSKU', {}, {}).save(para, function(res){
					if (res.errcode != 0) {
						toaster.error({ title: '', body: res.errmsg });
						return;
					}
					toaster.success({title: '', body: '成功'});
				});

			};

			scope.addStandard = function(){
				scope.tabletitle.push({'id': new Date().getTime(), 'sku_type': '', 'list': []});
			}
			scope.deleteStandard = function(index){
				scope.tabletitle.splice(index, 1);
			}
			scope.addStandardItem = function(obj){
				if(!obj.sku_type){
					toaster.warning({ title: '', body: '请填写规格标准后再添加'});
					return;
				}
				var a = obj.list.length - 1;
				a = obj.list[a]?obj.list[a].id:0;
				obj.list.push({'id': a+1, 'sku_name': '', 'is_check': '1'});
			}
			scope.removeItem = function(index, obj){
				obj.list.splice(index, 1);
			}
			//flag是否主动刷新，主动（用户页面点击按钮），被动（进入页面的初始化加载）
			scope.refresh = function(flag){
				if(scope.tabletitle.length == 0){
					if(flag) toaster.warning({title: '', body: '请先添加规格项，在刷新表格'});
					return;
				}
				
				scope.skulist = [];
				scope.formdata.showitem = [];
				//先将规格项二维数组转为整合为一维数组
				for(var i = 0; i < scope.tabletitle.length; i++){
					var temp1 = scope.tabletitle[i];
					if(temp1.sku_type){
						if(temp1.list.length == 0) continue;
						scope.formdata.showitem.push(temp1.sku_type);
						var count = 0;
						for(var j = temp1.list.length-1; j >= 0; j--){
							var temp2 = temp1.list[j];
							if(temp2.sku_name){
								if(temp2.is_check == '1'){
									count++;
								}
								temp2.sku_type = temp1.sku_type;
								temp2.num = count;
								temp2.sku_type_sort = i;
								scope.skulist.push(temp2);
							}
						}
					} else {
						toaster.warning({title: '', body: '第' + (i+1) + '项规格名称为空'});
						return;
					}
				}
				if(scope.tabledata.length > 0){
					recordMoney(scope.tabledata);
				}
				//将整合后的一维数组制作成表格形式
				scope.tabledata = [];
				var i2 = scope.skulist.length - 1;
				var end = 1, flag = true, every_num = 1;
				for(; i2 >= 0; i2--){
					var temp1 = scope.skulist[i2];
					if(temp1.is_check == '0'){
						continue;
					}
					if(temp1.sku_type_sort + 1 == scope.formdata.showitem.length){
						var data1 = {};
						data1['name'+temp1.sku_type_sort] = temp1.sku_name;
						data1['rowspan'+temp1.sku_type_sort] = 1;
						scope.tabledata.push(data1);
					} else {
						for(var j = 0; j < end; j++){
							var temp2 = scope.tabledata[j];
							if(temp2['name'+temp1.sku_type_sort]){
								var temp3 = angular.copy(temp2);
								temp3['name'+temp1.sku_type_sort] = temp1.sku_name;
								scope.tabledata.push(temp3);
							} else {
								temp2['name'+temp1.sku_type_sort] = temp1.sku_name;
								temp2['rowspan'+temp1.sku_type_sort] = end;
							}
						}
					}
					if(flag){
						every_num = temp1.num;
						flag = false;
					}
					if(temp1.num == 1){
						end = end * every_num;
						flag = true;
					}
				}
				if(back_data){
					setTabelData(scope.tabledata, back_data);
				}
			}

			function recordMoney(list){
				var a = scope.formdata.showitem.length;
				list.forEach(element => {
					var sku = '';
					for(var i = 0; i < a; i++){
						sku += ',' + element['name'+i];
					}
					sku = sku.substring(1);
					back_data[sku] = element;
				});
			}

			function getSKUlist() {
				$resource('/api/ac/tc/ticketSaleSKUService/getSaleSKUList', {}, {})
				  .save({'sale_code':scope.saleobj.code}, function(res){
					if (res.errcode != 0) {
						toaster.error({ title: '', body: '获取产品规格信息失败'});
						return;
					}
					back_data = res.data.price_list;
					//将查询结果集中sku解析为页面可显示的二维数组
					res.data.sku_list.forEach(element => {
						var temp = scope.tabletitle[scope.tabletitle.length-1];
						if(!temp || (temp && temp.sku_type != element.sku_type)){
							temp = {
								'id': element.sku_type_sort,
								'sku_type': element.sku_type,
								'list': [{
									'id': parseInt(element.id),
									'sku_name': element.sku_name,
									'is_check': element.is_check
								}]
							}
							scope.tabletitle.push(temp);
						} else {
							temp.list.push({
								'id': parseInt(element.id),
								'sku_name': element.sku_name,
								'is_check': element.is_check
							});
						}
					});
					scope.refresh(false);
				});
			}
			getSKUlist();

			
		}
	};

};


